package com.ayf.payment.game.api.controller;

import com.ayf.payment.game.api.dto.MerchantDTO;
import com.ayf.payment.game.api.dto.PartitionChangeDTO;
import com.ayf.payment.game.api.dto.PartitionDTO;
import com.ayf.payment.game.api.dto.criteria.PartitionCriteria;
import com.ayf.payment.game.api.dto.criteria.PartitionPageCriteria;
import com.ayf.payment.game.api.dto.criteria.PartitionSelectCriteria;
import com.ayf.payment.game.api.entity.Partition;
import com.ayf.payment.game.api.entity.Template;
import com.ayf.payment.game.api.exception.BusinessException;
import com.ayf.payment.game.api.exception.InvalidEncryptedKeyException;
import com.ayf.payment.game.api.mapper.TemplateMapper;
import com.ayf.payment.game.api.service.PartitionService;
import com.ayf.payment.game.api.type.CommonConstants;
import com.ayf.payment.game.api.type.Status;
import com.ayf.payment.game.api.utils.CommonResult;
import com.ayf.payment.game.api.utils.MD5Util;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 分区管理
 *
 * @author wwl
 * @date 2019/12/5 10:11
 */
@RequestMapping("/v/partition")
@RestController
public class PartitionController {

    @Autowired
    private PartitionService partitionService;

    @Resource
    private TemplateMapper templateMapper;

    @PostMapping("/selectPage")
    public CommonResult<PageInfo> selectPage(MerchantDTO merchantDTO, @RequestBody PartitionPageCriteria selectCriteria) {
        PageHelper.startPage(selectCriteria.getPageNum(), selectCriteria.getPageSize());
        selectCriteria.setMerchantId(merchantDTO.getId());

        List<PartitionDTO> list = partitionService.selectByPage(selectCriteria);
        PageInfo pageInfo = new PageInfo(list);
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, CommonConstants.OPERATION_SUCCESS, pageInfo);
    }

    /**
     * 查询未删除的分区列表
     * @param merchantDTO
     * @param selectCriteria
     * @return
     */
    @PostMapping("/selectAll")
    public CommonResult<List<PartitionDTO>> selectEnablePartition(MerchantDTO merchantDTO, @RequestBody PartitionSelectCriteria selectCriteria) {
        selectCriteria.setMerchantId(merchantDTO.getId());
        selectCriteria.setPartitionStatus(Status.ENABLE.name());
        List<PartitionDTO> list = partitionService.selectByDTO(selectCriteria);
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, CommonConstants.OPERATION_SUCCESS, list);
    }

    /**
     * 查询商户分区列表
     * @param merchantDTO
     * @return
     */
    @PostMapping("/getListAll")
    public CommonResult<List<PartitionDTO>> selectPartitionAll(MerchantDTO merchantDTO) {
        PartitionSelectCriteria selectCriteria=new PartitionSelectCriteria();
        selectCriteria.setMerchantId(merchantDTO.getId());
        selectCriteria.setPartitionStatus(Status.ENABLE.name());
        List<PartitionDTO> list = partitionService.getPartitionList(selectCriteria);
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, CommonConstants.OPERATION_SUCCESS, list);
    }

    /**
     * 查询全部分区列表
     * @param merchantDTO
     * @param selectCriteria
     * @return
     */
    @PostMapping("/selectAllPartitionList")
    public CommonResult<List<PartitionDTO>> selectAllPartition(MerchantDTO merchantDTO, @RequestBody PartitionSelectCriteria selectCriteria) {
        selectCriteria.setMerchantId(merchantDTO.getId());
        List<PartitionDTO> list = partitionService.selectByDTO(selectCriteria);
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, CommonConstants.OPERATION_SUCCESS, list);
    }

    /**
     * wx-查询分区列表
     *
     * @param selectCriteria
     * @return
     */
    @PostMapping("/wxSelectAll")
    public CommonResult<List<PartitionDTO>> wxSelectPartitionDto(HttpServletRequest request, @RequestBody PartitionSelectCriteria selectCriteria,
                                                                 @RequestHeader("signStr") String signStr) {
        String sign = MD5Util.sign(selectCriteria.getMerchantId().toString(), null);
        if (!StringUtils.equals(sign, signStr)) {
            LogPortal.error("WX_SELECT_PARTITION_VERIFY_FAIL >>> 微信公众号端查询分区列表-验签失败: 请求URL[{}],商户号[{}],签名[{}]",
                    request.getRequestURL(),
                    selectCriteria.getMerchantId(), signStr);
            return new CommonResult<>(CommonConstants.RETURN_ERROR, "非法请求", null);
        }
        //验签成功，开始查询分区列表
        selectCriteria.setPartitionStatus(Status.ENABLE.name());
        List<PartitionDTO> list = partitionService.selectByDTO(selectCriteria);
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, CommonConstants.OPERATION_SUCCESS, list);
    }

    /**
     * 创建分区
     * @param merchantDTO
     * @param entity
     * @return
     */
    @PostMapping("/createPartition")
    public CommonResult createPartition(MerchantDTO merchantDTO, @RequestBody PartitionCriteria entity){
        entity.setMerchantId(merchantDTO.getId());
        Template template = templateMapper.selectByPrimaryKey(entity.getTemplateId());
        if (template ==null){
            return new CommonResult<>(CommonConstants.RETURN_ERROR, CommonConstants.OPERATION_ERROR, false);
        }
        if (!merchantDTO.getId().equals(template.getMerchantId())){
            return new CommonResult<>(CommonConstants.RETURN_ERROR, CommonConstants.OPERATION_ERROR, false);
        }
        Partition partition=partitionService.createPartition(entity);
        if(partition!=null) {
            if (entity.getIsCScript() == 1 && !"─────────────".equals(entity.getPartitionName())) {
                return  partitionService.loadPartition(partition.getMerchantId(), partition.getId(), 0,merchantDTO.getOperIp());
            }
        }
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, CommonConstants.OPERATION_SUCCESS, "");
    }

    /**
     * 王者开区助手专用-创建分区
     * @param merchantDTO
     * @param entity
     * @return
     */
    @PostMapping("/createPartition2")
    public CommonResult createPartition2(MerchantDTO merchantDTO, @RequestBody PartitionCriteria entity){
        entity.setMerchantId(merchantDTO.getId());
        Template template = templateMapper.selectByPrimaryKey(entity.getTemplateId());
        if (template ==null){
            return new CommonResult<>(CommonConstants.RETURN_ERROR, CommonConstants.OPERATION_ERROR, false);
        }
        if (!merchantDTO.getId().equals(template.getMerchantId())){
            return new CommonResult<>(CommonConstants.RETURN_ERROR, CommonConstants.OPERATION_ERROR, false);
        }
        Partition partition=partitionService.createPartition(entity);
        if(partition!=null) {
            return  partitionService.loadPartition(partition.getMerchantId(), partition.getId(), 0,merchantDTO.getOperIp());
        }
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, CommonConstants.OPERATION_SUCCESS, "");
    }

    /**
     * 加载分区
     * @param merchantDTO
     * @param criteria
     * @return
     */
    @PostMapping("/loadPartition")
    public CommonResult loadPartition(MerchantDTO merchantDTO, @RequestBody PartitionSelectCriteria criteria) throws InvalidEncryptedKeyException {
        if(StringUtils.isEmpty(criteria.getPartitionId())){
            throw new BusinessException(CommonConstants.RETURN_ERROR, "ID 为空");
        }
        CommonResult result= partitionService.loadPartition(merchantDTO.getId(),criteria.getPartitionId(),1,merchantDTO.getOperIp());
        return  result;
    }

    /**
     * 多选加载分区
     * @param merchantDTO
     * @param criteria
     * @return
     */
    @PostMapping("/loadPartitionList")
    public CommonResult loadPartitionList(MerchantDTO merchantDTO, @RequestBody PartitionSelectCriteria criteria) throws InvalidEncryptedKeyException {
        if((criteria.getPartitionIdList()==null || criteria.getPartitionIdList().length==0)){
            throw new BusinessException(CommonConstants.RETURN_ERROR, "请选择加载分区！");
        }
        Map<String,Object> mapResult=new HashMap<>();
        mapResult.put("totle",criteria.getPartitionIdList().length);

        int finsh=0;
        int fail=0;
        StringBuffer buffer=new StringBuffer();
            for (String partitionId:criteria.getPartitionIdList()) {
                CommonResult result= partitionService.loadPartition(merchantDTO.getId(),partitionId,1,merchantDTO.getOperIp());
                if(result.getCode()==200){
                    finsh=finsh+1;
                }else{
                    fail=fail+1;
                    buffer.append(partitionId).append(":").append(result.getMsg()).append("<br/>");
                }
            }
        mapResult.put("finsh",finsh);
        mapResult.put("fail",fail);
        mapResult.put("errorMsg",buffer.toString());
        return  new CommonResult(CommonConstants.RETURN_SUCCESS, "分区加载完成!", mapResult);
    }


    /**
     * 克隆分区
     * @param merchantDTO
     * @param criteria
     * @return
     */
    @PostMapping("/clonePartition")
    public CommonResult clonePartition(MerchantDTO merchantDTO, @RequestBody PartitionSelectCriteria criteria){
        if(StringUtils.isEmpty(criteria.getPartitionId())){
            throw new BusinessException(CommonConstants.RETURN_ERROR, "ID 为空");
        }
        Template template = templateMapper.selectByPrimaryKey(criteria.getTemplateId());
        if (template ==null){
            return new CommonResult<>(CommonConstants.RETURN_ERROR, CommonConstants.OPERATION_ERROR, false);
        }
        if (!merchantDTO.getId().equals(template.getMerchantId())){
            return new CommonResult<>(CommonConstants.RETURN_ERROR, CommonConstants.OPERATION_ERROR, false);
        }
       String newId= partitionService.clonePartition(merchantDTO.getId(),criteria.getPartitionId());
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, CommonConstants.OPERATION_SUCCESS, newId);
    }

    /**
     * 查找分区
     * @param merchantDTO
     * @param criteria
     * @return
     */
    @PostMapping("/find")
    public CommonResult<PartitionChangeDTO> findPartition(MerchantDTO merchantDTO, @RequestBody PartitionSelectCriteria criteria){
        if(StringUtils.isEmpty(criteria.getPartitionId())){
            throw new BusinessException(CommonConstants.RETURN_ERROR, "ID 为空");
        }
        PartitionChangeDTO entity= partitionService.selectPartitionChangeDTO(merchantDTO.getId(),criteria.getPartitionId());
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, CommonConstants.OPERATION_SUCCESS, entity);
    }

    /**
     * 逻辑删除分区
     * @param merchantDTO
     * @param criteria
     * @return
     */
    @PostMapping("/del")
    public CommonResult<String> delPartition(MerchantDTO merchantDTO, @RequestBody PartitionSelectCriteria criteria){
        if (criteria.getPartitionIdList() != null && criteria.getPartitionIdList().length>0) {
            for (String partitionId:criteria.getPartitionIdList()) {
                Partition partition=partitionService.find(merchantDTO.getId(),partitionId);
                if(partition==null){
                    throw new BusinessException(CommonConstants.RETURN_ERROR, "分区ID["+partitionId+"]记录不存在");
                }
                partition.setOperIp(merchantDTO.getOperIp());
                partitionService.delete(partition);
            }
            return new CommonResult<String>(CommonConstants.RETURN_SUCCESS,"批量删除分区成功", "");
        }
        if (StringUtils.isEmpty(criteria.getPartitionId())){
            throw new BusinessException(CommonConstants.RETURN_ERROR, "分区ID不能为空");
        }
        Partition partition=partitionService.find(merchantDTO.getId(),criteria.getPartitionId());
        if(partition==null){
            throw new BusinessException(CommonConstants.RETURN_ERROR, "分区ID[{"+criteria.getPartitionId()+"}]记录不存在");
        }
        partition.setOperIp(merchantDTO.getOperIp());
        partitionService.delete(partition);
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS,"分区删除成功", "");
    }


    /**
     * 修改更新分区
     * @param merchantDTO
     * @param entity
     * @return
     */
    @PostMapping("/update")
    public CommonResult updatePartition(MerchantDTO merchantDTO, @RequestBody PartitionCriteria entity){
        entity.setMerchantId(merchantDTO.getId());
        Template template = templateMapper.selectByPrimaryKey(entity.getTemplateId());
        if (template ==null){
            return new CommonResult<>(CommonConstants.RETURN_ERROR, CommonConstants.OPERATION_ERROR, false);
        }
        if (!merchantDTO.getId().equals(template.getMerchantId())){
            return new CommonResult<>(CommonConstants.RETURN_ERROR, CommonConstants.OPERATION_ERROR, false);
        }
        LogPortal.debug("分区修改-商户ID[{}]-分区编号[{}] 参数:{}",merchantDTO.getId(),entity.getId(),entity.toString());
        partitionService.updatePartition(entity);
        if (entity.getIsCScript() == 1) {
          return  partitionService.loadPartition(entity.getMerchantId(), entity.getId(), 1,merchantDTO.getOperIp());
        }
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, CommonConstants.OPERATION_SUCCESS, "");
    }

    @PostMapping("/testingWateGay")
    public CommonResult testingWateGay(MerchantDTO merchantDTO, @RequestBody PartitionSelectCriteria criteria){
        if(StringUtils.isEmpty(criteria.getPartitionId())){
            throw new BusinessException(CommonConstants.RETURN_ERROR, "ID 为空");
        }
        criteria.setMerchantId(merchantDTO.getId());
        return partitionService.testingWateGay(criteria);
    }

    /**
     * 查询分区信息（充值时调用）
     *
     * @param criteria
     * @return
     */
    @PostMapping("/getAllPartition")
    public CommonResult<List<PartitionDTO>> getAllPartition(@RequestBody PartitionCriteria criteria){
        List<PartitionDTO> info = partitionService.selectPartitionInfo(criteria);
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS,"查询成功",info);
    }

    /**
     * 修改分区排序序号
     * @param criteria
     * @return
     */
    @PostMapping("/updatePartitionSort")
    public CommonResult updatePartitionSort(MerchantDTO merchantDTO,@RequestBody PartitionCriteria criteria){
        Partition  partition= partitionService.find(merchantDTO.getId(),criteria.getPartitionId());
        if (partition == null){
            throw new BusinessException(CommonConstants.RETURN_ERROR, "分区ID:"+criteria.getPartitionId()+"记录不存在");
        }
        partitionService.updatePartitionSort(criteria);
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, CommonConstants.OPERATION_SUCCESS, "");
    }

    /**
     * 修改分区是否开区标识
     * @param merchantDTO
     * @param entity
     * @return
     */
    @PostMapping("/updateIsOpen")
    public CommonResult updateIsOpen(MerchantDTO merchantDTO, @RequestBody PartitionCriteria entity){
        Partition  partition= partitionService.find(merchantDTO.getId(),entity.getPartitionId());
        if (partition == null){
            throw new BusinessException(CommonConstants.RETURN_ERROR, "分区ID:"+entity.getPartitionId()+"记录不存在");
        }
        partitionService.updateByStatus(partition);
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, CommonConstants.OPERATION_SUCCESS, "");
    }
}
